<template>
  <div class="box">
    <div class="header">
      <el-button type="primary" :icon="Plus" solid @click="openDialog('add')">添加网红小店</el-button>
    </div>
    <div class="content">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="name" label="名字" width="180" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="url" label="小店图片">
          <template #default="scope">
            <img v-if="scope.row.url && scope.row.url.length > 0" class="whxd-img" :src="scope.row.url[0]" alt="小店图片">
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="label" label="小店标签">
          <template #default="scope">
            <el-tag v-for="(item, index) in scope.row.label" :key="index" type="warning">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessHours" label="营业时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="success" :icon="Edit" @click="openDialog('edit', scope.row)">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="deleteItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog 
      v-model="whxdVisible" 
      :title="dialogType === 'add' ? '新增网红小店' : '编辑网红小店'" 
      width="500" 
      center
      @close="handleDialogClose"
    >
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto">
        <el-form-item label="店铺名称" prop="name" :rules="[{ required: true, message: '请输入店铺名称', trigger: 'blur' }]">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="店铺地址" prop="address" :rules="[{ required: true, message: '请输入店铺地址', trigger: 'blur' }]">
          <el-input v-model="ruleForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-select v-model="ruleForm.startTime" style="width: 140px" :max-time="ruleForm.endTime"
            placeholder="开始时间" start="00:00" step="00:30" end="23:59" />
          <el-time-select v-model="ruleForm.endTime" style="width: 140px" :min-time="ruleForm.startTime"
            placeholder="结束时间" start="00:00" step="00:30" end="23:59" />
        </el-form-item>
        <el-form-item label="店铺标签" prop="label">
          <el-input-tag v-model="ruleForm.label" placeholder="请输入标签" aria-label="请输入后敲击回车" />
        </el-form-item>
        <el-form-item label="店铺介绍" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import data from '@/utils/data';
import { ref, onMounted } from 'vue';

const tableData = ref([]);
console.log(data, 'data');
const whxdVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = ref({
  name: '',
  address: '',
  startTime: '',
  endTime: '',
  urllist: [],
  label: [],
  remark: '',
});
const dialogType = ref('add');
let whxdId = ref(null);
let originalFormData = ref({}); // 用于存储编辑前的原始表单数据

onMounted(() => {
  const savedData = localStorage.getItem('whxdData');
  tableData.value = savedData ? JSON.parse(savedData) : data;
});

const openDialog = (type, row = null) => {
  whxdVisible.value = true;
  if (type === 'edit' && row) {
    dialogType.value = 'edit';
    whxdId.value = row.id;
    // 深拷贝原始数据，用于取消时恢复
    originalFormData.value = JSON.parse(JSON.stringify(row));
    ruleForm.value = JSON.parse(JSON.stringify(row));
    const [start, end] = row.businessHours.split(' - ');
    ruleForm.value.startTime = start;
    ruleForm.value.endTime = end;
  } else {
    dialogType.value = 'add';
    whxdId.value = null;
    // 重置表单和原始数据存储
    ruleForm.value = {
      name: '',
      address: '',
      startTime: '',
      endTime: '',
      urllist: [],
      label: [],
      remark: '',
    };
    originalFormData.value = {};
  }
};

const deleteItem = (index) => {
  tableData.value.splice(index, 1);
  localStorage.setItem('whxdData', JSON.stringify(tableData.value));
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const newData = {
        id: whxdId.value || (tableData.value.length > 0 ? Math.max(...tableData.value.map(item => item.id || 0)) + 1 : 1),
        name: ruleForm.value.name,
        address: ruleForm.value.address,
        businessHours: `${ruleForm.value.startTime || ''} - ${ruleForm.value.endTime || ''}`,
        url: ruleForm.value.url || [],
        label: ruleForm.value.label || [],
        remark: ruleForm.value.remark || '',
      };
      if (whxdId.value) {
        const index = tableData.value.findIndex(item => item.id === whxdId.value);
        tableData.value[index] = newData;
      } else {
        tableData.value.push(newData);
      }
      localStorage.setItem('whxdData', JSON.stringify(tableData.value));
      whxdVisible.value = false;
    } else {
      console.log('表单验证失败', fields);
    }
  });
};

// 处理对话框关闭（点击×按钮）
const handleDialogClose = () => {
  cancelForm();
};

// 处理取消按钮点击
const cancelForm = () => {
  if (dialogType.value === 'edit') {
    // 恢复编辑前的原始数据
    ruleForm.value = JSON.parse(JSON.stringify(originalFormData.value));
    const [start, end] = originalFormData.value.businessHours.split(' - ');
    ruleForm.value.startTime = start;
    ruleForm.value.endTime = end;
  } else {
    // 新增时直接重置表单
    ruleForm.value = {
      name: '',
      address: '',
      startTime: '',
      endTime: '',
      urllist: [],
      label: [],
      remark: '',
    };
  }
  whxdVisible.value = false;
};
</script>

<style scoped lang="scss">
.box {
  padding: 20px;

  .header {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    margin-top: 20px;

    .whxd-img {
      width: 100px;
      height: 100px;
    }
  }
}
</style>